import re

from django.contrib.auth.backends import ModelBackend

from apps.users.models import Users


class UsernameMobileAuthBackend(ModelBackend):
    """用户认证"""

    def authenticate(self, request, username=None, password=None, **kwargs):

        user = self.get_account_by(account=username)
        if user and user.check_password(password):
            return user

    @staticmethod
    def get_account_by(account):

        try:
            if re.match(r'^1[3-9]\d{9}', account):
                user = Users.objects.get(mobile=account)
            else:
                user = Users.objects.get(username=account)
        except:
            return None

        else:
            return user
